package com.xpec.c4.db.basic;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.xpec.c4.db.hibernate.manager.HibernateBusinessManager;
import com.xpec.c4.db.model.log.basic.BasicLogModel;

public class BasicBusunessDAO {
	/**
	 * 存储日志对象
	 * 
	 * @param log
	 * @return author: zhongzhengkai date: 2011 2011-12-6 下午04:34:27
	 */
	public static boolean saveTransaction(BasicLogModel log) {
		HibernateBusinessManager.txBegin();
		save(log);
		boolean success = HibernateBusinessManager
				.txCommitFailRollbackClearSession();
		return success;
	}
	public static boolean saveLogs(List<? extends BasicLogModel> logs) {
		HibernateBusinessManager.txBegin();
		for (BasicLogModel log : logs) {
			save(log);
		}
		boolean success = HibernateBusinessManager
				.txCommitFailRollbackClearSession();
		return success;
	}
	/**
	 * 更新日志对象
	 * 
	 * @param log
	 * @return author: zhongzhengkai date: 2011 2011-12-6 下午04:33:16
	 */
	public static boolean updateTransaction(BasicLogModel log) {
		HibernateBusinessManager.txBegin();
		 update(log);
		boolean success = HibernateBusinessManager
				.txCommitFailRollbackClearSession();
		return success;
	}

	/**
	 * @param clazz
	 * @param parameters
	 * @return 删除的记录条数 author: zhongzhengkai date: 2011 2011-12-6 下午04:32:06
	 */
	public static int deleteLogTransaction(BasicLogModel log) {
		HibernateBusinessManager.txBegin();
		Class<? extends BasicLogModel> logClass = log.getClass();
		HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("eventId",  log.getEventId());
			int i = delete(logClass, map);
			HibernateBusinessManager.txCommitFailRollbackClearSession();
			return i;
	}
	/**
	 * 保存实体对象
	 * @param entity 待保存的实体对象
	 */
	public static void save(BasicLogModel entity){
		if(entity==null){
			return;
		}
		Session session=HibernateBusinessManager.getSession();
		session.save(entity);
	}
	
	/**
	 * 更新实体对象
	 * @param entity 待更新的实体对象
	 */
	public static void update(BasicLogModel entity){
		Session session=HibernateBusinessManager.getSession();
		session.update(entity);
	}
	
	/**
	 * 保存或更新实体对象
	 * @param entity 待处理的实体对象
	 */
	public static void saveOrUpdate(BasicLogModel entity){
		Session session=HibernateBusinessManager.getSession();
		session.saveOrUpdate(entity);
	}
	
	/**
	 * 删除实体对象
	 * @param entity 待删除的实体对象
	 */
	public static void delete(BasicLogModel entity){
		Session session=HibernateBusinessManager.getSession();
		session.delete(entity);
	}
	
	/**
	 * 从数据库读取指定的实体对象
	 * @param clazz
	 * @param db_id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends BasicLogModel>T get(Class<T> clazz, Serializable db_id){
		Session session=HibernateBusinessManager.getSession();
		Object obj=session.get(clazz, db_id);
		return (T)obj;
	}
	
	/**
	 * 从数据库读取指定的实体对象
	 * @param clazz
	 * @param db_id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends BasicLogModel>T load(Class<T> clazz, Serializable db_id){
		Session session=HibernateBusinessManager.getSession();
		Object obj=session.load(clazz, db_id);
		return (T)obj;
	}
	
	/**
	 * 从数据库读取指定的实体对象
	 * @param clazz
	 * @param db_id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends BasicLogModel> List<T> loadAll(Class<T> clazz){
		Session session=HibernateBusinessManager.getSession();
		Criteria cri=session.createCriteria(clazz);
		return cri.list();
	}
	
	/**
	 * 执行指定的SQL语句
	 * @param command
	 * @return
	 */
	public static int execute(String command){
		Session session=HibernateBusinessManager.getSession();
		Query query=session.createSQLQuery(command);
		return query.executeUpdate();
	}
	
	/**
	 * LOG信息查询功能 修改成查询从数据库。
	 * 
	 * @param accountID
	 *            帐户ID
	 * @param firstResult
	 *            开始位置
	 * @param maxResults
	 *            记录长度
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends BasicLogModel> List<T> loadAndExpression(Class<T> clazz,
			HashMap<String, Object> parameters, int firstResult, int maxResults,String order) {
		Session session = HibernateBusinessManager.getSession();
		Criteria criteria = session.createCriteria(clazz);
		// 参数设置
		Set<String> keys = parameters.keySet();
		Object value;
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				criteria.add(Restrictions.eq(key, value));
			}
		}

		// 开始位置
		if (firstResult >= 0) {
			criteria.setFirstResult(firstResult);
		}
		
		// 记录长度
		if (maxResults >= 0) {
			criteria.setMaxResults(maxResults);
		}

		// 按时间排序
		criteria.addOrder(Order.asc(order));

		return criteria.list();
	}

	/**
	 * 查找符合条件的数据记录数量
	 * 
	 * @param clazz
	 *            操作的实体类
	 * @param parameters
	 *            参数
	 * @return
	 */
	public static Long getCountAndExpression(Class<? extends BasicLogModel> clazz,
			HashMap<String, Object> parameters) {
		
		Session session = HibernateBusinessManager.getSession();
		Criteria criteria = session.createCriteria(clazz);
		// 参数设置
		Set<String> keys = parameters.keySet();
		Object value;
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				criteria.add(Restrictions.eq(key, value));
			}
		}
		
		ProjectionList projection = Projections.projectionList();
		projection.add(Projections.count("db_id"));
		

		criteria.setProjection(projection);

		return (Long) criteria.uniqueResult();
	}

	/**
	 * 删除对应的LOG记录
	 * 
	 * @param clazz
	 *            操作的实体类
	 * @param parameters
	 *            参数值
	 */
	public static int delete(Class<? extends BasicLogModel> clazz, HashMap<String, Object> parameters) {
		Session session = HibernateBusinessManager.getSession();
		StringBuffer sql = new StringBuffer();
		sql.append("delete from ").append(clazz.getName()).append(
				" log where 1=1 ");

		// 设置HQL语句
		// 参数设置
		Set<String> keys = parameters.keySet();
		Object value;
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				sql.append(" and ").append(key).append(" = :").append(
						key.replace(".", "_"));
			}
		}

		Query query = session.createQuery(sql.toString());

		// 设置参数值
		// 参数设置
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				query.setParameter(key, value);
			}
		}

		return query.executeUpdate();
	}

	/**
	 * 查找符合条件的用户登录LOG的记录<br>
	 * 表达式的条件使用or关系
	 * 
	 * @param <T>
	 *            范型
	 * @param clazz
	 *            操作的实体类
	 * @param parameters
	 *            参数值
	 * @param firstResult
	 *            查找的开始偏移位置
	 * @param maxResults
	 *            查找的最大记录条数
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends BasicLogModel> List<T> loadOrExpression(Class<T> clazz,
			HashMap<String, Object> parameters, int firstResult,
			int maxResults, String order) {
		Session session = HibernateBusinessManager.getSession();
		StringBuffer sql = new StringBuffer();
		sql.append("from ").append(clazz.getName()).append(" log where 1=1 ");

		// 设置HQL语句
		// 参数设置
		StringBuffer orSql = new StringBuffer();
		Set<String> keys = parameters.keySet();
		Object value;
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				orSql.append(" or ").append(key).append(" = :").append(
						key.replace(".", "_"));
			}
		}

		if (orSql.length() > 1) {
			orSql.append(" )");
			sql.append(" and ( 1 = 2 ").append(orSql);
		}

		// 按排序
		if (order != null && order.length() > 0) {
			sql.append(" order by " + order + " asc ");
		}

		Query query = session.createQuery(sql.toString());

		// 设置参数值
		// 参数设置
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				query.setParameter(key.replace(".", "_"), value);
			}
		}

		if (firstResult >= 0) {
			query.setFirstResult(firstResult);
		}

		if (maxResults >= 0) {
			query.setMaxResults(maxResults);
		}

		return query.list();
	}

	/**
	 * 查找符合条件的用户登录LOG的记录数量<br>
	 * 表达式的条件使用or关系
	 * 
	 * @param clazz
	 *            操作的实体类
	 * @param parameters
	 *            参数
	 * @param beginTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @return
	 */
	public static int getCountOrExpression(Class<? extends BasicLogModel> clazz,
			HashMap<String, Object> parameters) {
		Session session = HibernateBusinessManager.getSession();
		StringBuffer sql = new StringBuffer();
		sql.append("select count(*) from ").append(clazz.getName()).append(
				" log where 1=1 ");

		// 设置HQL语句
		// 参数设置
		StringBuffer orSql = new StringBuffer();
		Set<String> keys = parameters.keySet();
		Object value;
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				orSql.append(" or ").append(key).append(" = :").append(
						key.replace(".", "_"));
			}
		}

		Query query = session.createQuery(sql.toString());

		// 设置参数值
		// 参数设置
		for (String key : keys) {
			value = parameters.get(key);
			if (key != null && value != null && value.toString().length() > 0) {
				query.setParameter(key.replace(".", "_"), value);
			}
		}

		query.setMaxResults(1);

		return (Integer)query.uniqueResult();
	}
}
